<template>
    <div class="purchase-apply-container">
        <el-card class="form-card">
            <template #header>
                <div class="card-header">
                    <span class="form-title">{{ isEdit ? '修改采购询价单' : '采购询价单' }}</span>
                    <div class="header-actions">
                        <el-button>商品记录</el-button>
                        <el-button type="primary" @click="handleSubmit" :disabled="!selectedSupplier.SupplierName">{{
                            isEdit ? '保存修改' : '保存并新增' }}</el-button>
                        <el-button type="primary" @click="handleSubmit2"
                            :disabled="!selectedSupplier.SupplierName">保存</el-button>
                        <el-button>批量导入</el-button>
                        <el-button @click="audit" v-if="!isEdit">审核</el-button>
                    </div>
                </div>
            </template>
            <div class="form-content">
                <el-form :model="form" label-width="100px" class="fixed-height-dialog" width="60%">
                    <!-- 供应商信息头部 -->
                    <div class="supplier-header">
                        <div class="supplier-info-row">
                            <div class="info-item">
                                <span class="label">供应商:</span>
                                <el-input v-model="selectedSupplier.SupplierName" placeholder="选择供应商(必选)" clearable
                                    disabled style="width: 180px; margin-right: 20px;">
                                    <template #append>
                                        <el-button :icon="Search" @click="supplierDialog.open()" />
                                    </template>
                                </el-input>
                                <span class="label">询价人:</span>
                                <el-input v-model="form.buyer_name" placeholder="" clearable style="width: 120px;" disabled>
                                </el-input>
                            </div>
                            <div class="info-item">
                                <span class="label">有效日期:</span>
                                <el-date-picker v-model="tempDateRange" type="datetimerange" range-separator="~"
                                    start-placeholder="开始日期" end-placeholder="结束日期" style="width: 400px;"
                                    @change="handleDateRangeChange" />
                            </div>
                        </div>
                        <div class="supplier-detail-row" v-if="isEdit == false">
                            <div class="info-item">
                                <span class="label">供应商发货地址:</span>
                                <el-input v-model="selectedSupplier.supplierAddress" placeholder="供应商发货地址" clearable
                                    style="width: 300px;" />
                            </div>
                        </div>
                    </div>

                    <!-- 采购物品明细 -->
                    <div class="form-section">
                        <div class="section-header">
                            <div class="section-title">
                                采购订单明细
                                <el-button type="primary" link @click="openGoodsDialog" style="margin-left: 10px;">
                                    <el-icon>
                                        <Plus />
                                    </el-icon>添加物品
                                </el-button>
                                <span class="item-count" v-if="form.inquiryDetailList.length > 0">
                                    共 {{ form.inquiryDetailList.length }} 个物品
                                </span>
                            </div>
                        </div>

                        <el-table :data="form.inquiryDetailList" border style="width: 100%" class="items-table"
                            empty-text="暂无物品，请点击添加物品">
                            <el-table-column label="序号" type="index" width="60" align="center" />
                            <el-table-column label="商品编号" prop="goods_code" width="120" />
                            <el-table-column label="物品名称" prop="goods_name" min-width="150" />
                            <el-table-column label="备注" prop="supplier_remark" min-width="120" />
                            <el-table-column label="报价税率" prop="supplier_quote_tex" width="100">
                                <template #default="{ row }">
                                    <el-input-number v-model="row.supplier_quote_tex" :min="0" :precision="2"
                                        controls-position="right" style="width: 100px" />
                                </template>
                            </el-table-column>
                            <el-table-column label="报价单价" prop="supplier_quote_price" width="120" align="right">
                                <template #default="{ row }">
                                    <el-input-number v-model="row.supplier_quote_price" :min="0" :precision="2"
                                        controls-position="right" style="width: 100px" />
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="80" align="center" fixed="right">
                                <template #default="{ $index }">
                                    <el-button type="danger" link @click="removeItem($index)">
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <!-- 其他信息 -->
                    <div class="supplier-detail-row" style="margin-bottom: 20px;">
                        <el-input v-model="form.remark" placeholder="暂无备注信息" type="textarea" />
                    </div>
                    <div class="supplier-detail-row" style="margin-bottom: 12px;">
                        <span class="label">优惠率 :</span>
                        <el-input v-model="form.youhuilv" clearable style="width: 100px; " />
                        <span class="label">付款优惠:</span>
                        <el-input v-model="form.youhuilv" clearable style="width: 100px; " />
                        <span class="label">优惠后金额:</span>
                        <el-input v-model="form.youhuilv" clearable style="width: 100px; " disabled />
                        <span class="label">本次付款:</span>
                        <el-input v-model="form.youhuilv" clearable style="width: 100px; " />
                        <span class="label">结算账户:</span>
                        <el-select v-model="form.buyer" placeholder="" clearable style="width: 120px;">
                            <el-option value="1">微信支付</el-option>
                            <el-option value="2">现金支付</el-option>
                            <el-option value="3">自配送</el-option>
                            <el-option value="白玛">白玛</el-option>
                        </el-select>
                    </div>
                    <div class="supplier-detail-row">
                        <span class="label">本次欠款:</span>
                        <el-input v-model="form.youhuilv" clearable style="width: 100px;" disabled />
                        <span class="label">总欠款:</span>
                        <el-input v-model="form.youhuilv" clearable style="width: 100px; " disabled />
                        <span class="label">采购费用:</span>
                        <el-input v-model="form.youhuilv" clearable style="width: 100px; " disabled />
                        <span class="label">结算方式:</span>
                        <el-select v-model="form.gateWay" placeholder="业务员" clearable style="width: 120px;">
                            <el-option value="1">快递物流</el-option>
                            <el-option value="2">自提</el-option>
                            <el-option value="3">自配送</el-option>
                            <el-option value="白玛">白玛</el-option>
                        </el-select>
                    </div>
                </el-form>
            </div>
        </el-card>

        <!-- 商品选择对话框 -->
        <!-- <el-dialog v-model="openGoodsDialogView" title="选择商品" width="80%">
            <SelectGoods :visible="openGoodsDialogView" @update:visible="openGoodsDialogView = $event"
                @confirm="handleGoodsConfirm" />
        </el-dialog> -->

        <!-- 商品搜索列表弹出对话框 -->
        <el-dialog v-model="openGoodsDialogView" title="商品搜索列表" width="40%" style="height: auto; width: 800px;"
            draggable :show-close="true">
            <!-- 调用商品的搜索组件 -->
            <FreeGoodsSelect v-model="openGoodsDialogView" @update:visible="openGoodsDialogView = $event"
                @confirm="handleGoodsConfirm">
            </FreeGoodsSelect>
            <br /><br />
        </el-dialog>

        <!-- 供应商对话框 -->
        <SupplierDialog ref="supplierDialog" :supplier-list="SupplierList" @confirm="handleSupplierConfirm" />
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
// import SelectGoods from './SelectGoods.vue'
import FreeGoodsSelect from "@/util/FreeGoodsSelect.vue";
import SupplierDialog from '@/util/SupplierDialog.vue'
import axios from 'axios'

const route = useRoute()
const router = useRouter()


// 判断是否为编辑模式
const isEdit = computed(() => route.query.isEdit === 'true')

// 对话框引用
const supplierDialog = ref(null);

// 选择的供应商
const selectedSupplier = reactive({
    SupplierName: '',
    SupplierConcat: '',
    SupplierPhone: '',
    supplierAddress: '',
    totalDebt: 0
});

// 表单数据
const form = reactive({
    inquiry_id: '',
    inquiry_code: '',
    buyer_code: '',
    buyer_name: sessionStorage.getItem("name"),
    inquiry_supplier: '',
    supplier_code: '',
    inquiry_startDate: '',
    inquiry_deadline: '',
    remark: '',
    companyCode: 'COMP001',
    isDelete: '0',
    inquiry_status: '1',
    checkMan: '',
    gateWay: '',
    printNum: '0',
    date_status: '1',
    inquiryDetailList: []
})

// 临时存储日期范围
const tempDateRange = ref([])

// 选择添加的商品
const openGoodsDialogView = ref(false)

// 组件挂载时检查是否为编辑模式
onMounted(() => {
    console.log("用户id",sessionStorage.getItem("staffId"))
    if (isEdit.value) {
        loadEditData()
    }
})

// 加载编辑数据
const loadEditData = async () => {
    try {
        // 从本地存储获取数据
        const inquiry_code = route.query.inquiry_code;
        if (!inquiry_code) return;

        const res = await axios.get(`/lxw/getInquiryByCode?inquiry_code=${inquiry_code}`);
        if (res.data.code == 5200) {
            const data = res.data.inquiryMain;

            // 填充主表单数据
            Object.assign(form, {
                inquiry_id: data.inquiry_id,
                inquiry_code: data.inquiry_code,
                buyer_code: data.buyer_code,
                buyer_name: data.buyer_name,
                inquiry_supplier: data.inquiry_supplier,
                supplier_code: data.supplier_code,
                inquiry_startDate: data.inquiry_startDate,
                inquiry_deadline: data.inquiry_deadline,
                remark: data.remark,
                checkMan: data.checkMan,
                gateWay: data.gateWay,
                printNum: data.printNum,
                companyCode:data.companyCode,
                inquiryDetailList: data.inquiryDetailList || []
            })

            // 填充供应商信息
            Object.assign(selectedSupplier, {
                SupplierName: data.inquiry_supplier,
                SupplierCode: data.supplier_code,
                supplierAddress: data.supplierAddress || ''
            })

            // 设置日期范围
            if (data.inquiry_startDate && data.inquiry_deadline) {
                tempDateRange.value = [
                    new Date(data.inquiry_startDate),
                    new Date(data.inquiry_deadline)
                ]
            }

            ElMessage.success('已加载编辑数据')
        }
    } catch (error) {
        console.error('加载编辑数据失败:', error)
        ElMessage.error('加载数据失败')
    }
}

const openGoodsDialog = () => {
    openGoodsDialogView.value = true;
}

// 处理选中的商品
const handleGoodsConfirm = (selectedGoods) => {
    console.log('选中的商品:', selectedGoods)

    if (selectedGoods && selectedGoods.length > 0) {
        // 转换商品数据格式，适配采购订单表格
        const newItems = selectedGoods.map(goods => ({
            goods_id:goods.id,
            goods_code: goods.code,
            goods_name: goods.name,
            supplier_remark: goods.remark,
            supplier_quote_price: 0,
            supplier_quote_tex: 0,
        }))

        // 添加到采购订单物品列表
        form.inquiryDetailList.push(...newItems);
        ElMessage.success(`成功添加 ${newItems.length} 个商品`);
    }
}

// 删除物品
const removeItem = (index) => {
    form.inquiryDetailList.splice(index, 1);
    ElMessage.success('删除成功');
}

// 保存并且新增
const handleSubmit = async () => {
    if (isEdit.value) {
        await handleModify()
    } else {
        await handleAdd(true)
    }
}

// 保存
const handleSubmit2 = async () => {
    if (isEdit.value) {
        await handleModify()
    } else {
        await handleAdd(false)
    }
}

// 新增询价单
const handleAdd = async (isAddNew) => {
    // 验证供应商
    if (!selectedSupplier.SupplierName) {
        ElMessage.warning('请选择供应商');
        return;
    }

    // 验证物品信息
    if (form.inquiryDetailList.length === 0) {
        ElMessage.warning('请至少添加一个采购物品');
        return;
    }

    try {
        await ElMessageBox.confirm('确定要提交采购订单吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });

        const orderData = {
            inquiry_code: form.inquiry_code,
            buyer_code: form.buyer_code,
            inquiry_supplier: form.inquiry_supplier,
            supplier_code: form.supplier_code,
            inquiry_startDate: formatDate(form.inquiry_startDate),
            inquiry_deadline: formatDate(form.inquiry_deadline),
            remark: form.remark,
            companyCode: form.companyCode,
            isDelete: form.isDelete,
            inquiry_status: form.inquiry_status,
            checkMan: form.checkMan,
            gateWay: form.gateWay,
            printNum: form.printNum,
            date_status: form.date_status,
            inquiryDetailList: form.inquiryDetailList
        };

        const res = await axios.post('/lxw/addInquiry', orderData, {
            headers: {
                'Content-Type': 'application/json'
            }
        });

        console.log(res)
        if (res.data.code == 5200) {
            ElMessage.success('订单提交成功！');
            if (isAddNew) {
                handleReset();
            }
        } else {
            ElMessage.error(res.data.msg);
        }
    } catch (error) {
        console.log('用户取消提交');
    }
}

// 修改询价单
const handleModify = async () => {
    // 验证供应商
    if (!selectedSupplier.SupplierName) {
        ElMessage.warning('请选择供应商');
        return;
    }

    // 验证物品信息
    if (form.inquiryDetailList.length === 0) {
        ElMessage.warning('请至少添加一个采购物品');
        return;
    }

    try {
        await ElMessageBox.confirm('确定要修改采购订单吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });

        const orderData = {
            inquiry_id: form.inquiry_id,
            inquiry_code: form.inquiry_code,
            buyer_code: form.buyer_code,
            inquiry_supplier: form.inquiry_supplier,
            supplier_code: form.supplier_code,
            inquiry_startDate: formatDate(form.inquiry_startDate),
            inquiry_deadline: formatDate(form.inquiry_deadline),
            remark: form.remark,
            companyCode: form.companyCode,
            isDelete: form.isDelete,
            inquiry_status: form.inquiry_status,
            checkMan: form.checkMan,
            gateWay: form.gateWay,
            printNum: form.printNum,
            date_status: form.date_status,
            inquiryDetailList: form.inquiryDetailList
        };

        const res = await axios.post('/lxw/modifyInquiry', orderData, {
            headers: {
                'Content-Type': 'application/json'
            }
        });

        console.log(res)
        if (res.data.code == 5200) {
            ElMessage.success('订单修改成功！');
            router.back();
        } else {
            ElMessage.error(res.data.msg);
        }
    } catch (error) {
        console.log('用户取消修改');
    }
}

// 日期格式化
const formatDate = (date) => {
    if (!date) return '';
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hours = String(d.getHours()).padStart(2, '0');
    const minutes = String(d.getMinutes()).padStart(2, '0');
    const seconds = String(d.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 重置表单
const handleReset = () => {
    Object.assign(selectedSupplier, {
        SupplierName: '',
        SupplierConcat: '',
        SupplierPhone: '',
        supplierAddress: '',
        totalDebt: 0
    });
    Object.assign(form, {
        inquiry_id: '',
        inquiry_code: '',
        buyer_code: '',
        inquiry_supplier: '',
        supplier_code: '',
        inquiry_startDate: '',
        inquiry_deadline: '',
        remark: '',
        companyCode: 'COMP001',
        isDelete: '0',
        inquiry_status: '1',
        checkMan: '',
        gateWay: '',
        printNum: '0',
        date_status: '1',
        inquiryDetailList: []
    });
    tempDateRange.value = [];
    ElMessage.info('表单已重置');
}

// 日期范围变化处理
const handleDateRangeChange = (dateRange) => {
    if (dateRange && dateRange.length === 2) {
        form.inquiry_startDate = dateRange[0]
        form.inquiry_deadline = dateRange[1]
    } else {
        form.inquiry_startDate = ''
        form.inquiry_deadline = ''
    }
}

// 审核方法
const audit = () => {
    // 实现审核逻辑
}

// 供应商数据
const SupplierList = ref([]);

// 处理供应商选择确认
const handleSupplierConfirm = (supplier) => {
    if (supplier) {
        Object.assign(selectedSupplier, supplier);
        ElMessage.success(`已选择供应商：${supplier.SupplierName || '空选'}`);
    } else {
        // 如果 supplier 是 null 或 undefined，清空 selectedSupplier
        Object.keys(selectedSupplier).forEach(key => {
            selectedSupplier[key] = '';
        });
        ElMessage.success('已选择空选');
    }
    form.inquiry_supplier = supplier?.SupplierName || '';
    form.supplier_code = supplier?.SupplierCode || '';
};
</script>

<style scoped>
.purchase-apply-container {
    height: 100%;
}

.form-card {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-actions {
    display: flex;
    align-items: center;
    gap: 20px;
}

.order-number {
    font-size: 14px;
    color: #606266;
}

.fixed-height-dialog {
    max-height: 80vh;
}

:deep(.fixed-height-dialog .el-dialog__body) {
    max-height: 60vh;
    overflow-y: auto;
    padding: 20px;
}

/* 供应商头部信息 */
.supplier-header {
    margin-bottom: 24px;
    padding: 16px;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    background-color: #fafafa;
}

.supplier-info-row,
.supplier-detail-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.supplier-detail-row {
    margin-bottom: 0;
}

.info-item {
    display: flex;
    align-items: center;
}

.label {
    font-size: 14px;
    color: #606266;
    margin-right: 8px;
    min-width: 80px;
}

.label.warning {
    color: #e6a23c;
}

.value {
    font-size: 14px;
    color: #303133;
}

.value.warning {
    color: #e6a23c;
    font-weight: bold;
}

/* 表单内容区域 - 可滚动 */
.form-content {
    flex: 1;
    overflow-y: auto;
    padding: 0 20px;
    max-height: calc(100vh - 200px);
}

/* 固定底部操作按钮 */
.form-footer {
    border-top: 1px solid #e8e8e8;
    padding: 16px 20px;
    background: #fff;
    position: sticky;
    bottom: 0;
    z-index: 10;
}

.form-actions {
    text-align: center;
}

/* 采购明细区域 */
.form-section {
    margin-bottom: 24px;
    padding: 16px;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    display: flex;
    align-items: center;
}

.section-actions {
    display: flex;
    align-items: center;
    gap: 20px;
}

.operator-info {
    font-size: 14px;
    color: #606266;
}

.item-count {
    margin-left: auto;
    font-size: 14px;
    color: #606266;
    margin-left: 10px;
}

.items-table {
    margin-bottom: 16px;
}

/* 总计区域 */
.total-summary {
    margin-top: 16px;
    padding: 16px;
    background-color: #f8f9fa;
    border-radius: 4px;
    border: 1px solid #e8e8e8;
}

.summary-row {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 40px;
}

.summary-item {
    display: flex;
    align-items: center;
}

.summary-label {
    font-size: 14px;
    color: #606266;
    margin-right: 8px;
}

.summary-value {
    font-size: 16px;
    font-weight: bold;
    color: #f56c6c;
}

.summary-value.total-amount {
    font-size: 18px;
    color: #f56c6c;
}

/* 优化表格样式 */
:deep(.items-table .el-table__empty-block) {
    min-height: 100px;
}

:deep(.items-table .el-table__empty-text) {
    color: #909399;
    font-size: 14px;
}

:deep(.el-upload__tip) {
    font-size: 12px;
    color: #909399;
    margin-top: 7px;
}
</style>